<template>
  <div class="note-add-page">
    <!-- 上部分 -->
    <div class="header">
      <el-button class="back-button" icon="el-icon-arrow-left" @click="goBack"></el-button>
      <div class="title">新增笔记</div>
      <el-button class="finish-button" type="primary" @click="finishNote" :disabled="noteTitle.length == 0">完成</el-button>
    </div>
    <!-- 中间部分编辑区 -->
    <div class="editor-container">
      <el-input
          v-model="noteTitle"
          placeholder="请输入标题"
          class="title-input"
      ></el-input>

      <div class="content-editor">
        <div ref="editor" class="quill-editor" @click="checkTableSelection"></div>
        <!--        <div v-if="showTableControls" class="table-controls">-->
        <!--          <el-button @click="addRow" class="table-control-button">添加行</el-button>-->
        <!--          <el-button @click="addColumn" class="table-control-button">添加列</el-button>-->
        <!--          <el-button @click="deleteRow" class="table-control-button">删除行</el-button>-->
        <!--          <el-button @click="deleteColumn" class="table-control-button">删除列</el-button>-->
        <!--        </div>-->
      </div>
    </div>

    <!-- 下部分区 -->
    <div class="bottom-toolbar">
      <el-button icon="el-icon-back" @click="undo" class="toolbar-button"></el-button>
      <el-button icon="el-icon-right" @click="redo" class="toolbar-button"></el-button>


      <!-- 新增的调整行列按钮 -->
      <el-button
          v-if="showTableControls"
          @click="showTableControlPopup = true"
          class="toolbar-button">调整行列</el-button>

      <el-button
          icon="el-icon-plus"
          @click="toggleAddMenu"
          class="toolbar-button add-button"
          ref="addButton"
      ></el-button>

    </div>

    <!-- 弹出层 -->
    <el-dialog
        :visible.sync="addMenuVisible"
        width="80vw"
        :show-close="false"
        custom-class="custom-add-menu"
        :modal="false"
    >
      <div class="add-menu-scroll-container">
        <div class="add-menu-content">
          <!--          图片-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertImage" class="icon-button">
                <i class="el-icon-picture"></i>
              </el-button>
            </div>
            <div class="text-container">插入图片</div>
          </div>
          <!--          声音-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertAudio" class="icon-button">
                <i class="el-icon-microphone"></i>
              </el-button>
            </div>
            <div class="text-container">插入声音</div>
          </div>
          <!--          表格-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertTable" class="icon-button">
                <i class="el-icon-tickets"></i>
              </el-button>
            </div>
            <div class="text-container">插入表格</div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 弹出层，用于调整行列 -->
    <el-dialog
        title="调整行列"
        :visible.sync="showTableControlPopup"
        width="80%">
      <div class="table-controls">
        <el-button @click="addRow" class="table-control-button">添加行</el-button>
        <el-button @click="addColumn" class="table-control-button">添加列</el-button>
        <el-button @click="deleteRow" class="table-control-button">删除行</el-button>
        <el-button @click="deleteColumn" class="table-control-button">删除列</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="showTableControlPopup = false">取 消</el-button>
      <el-button type="primary" @click="showTableControlPopup = false">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>
<script>
import Quill from 'quill';
import 'quill/dist/quill.snow.css'; // Quill 样式
import 'quill/dist/quill.bubble.css'; // 如果你打算使用 bubble 主题的话
import 'quill-table'; // quill-table 插件
export default {
  name: 'noteAdd',
  data() {
    return {
      noteTitle: '',
      quillEditor: null,
      addMenuVisible: false,
      showTableControls: false,
      tableIdCounter: 0, // 用于生成唯一的表格类名后缀
      selectedTableClass: null, // 存储当前选中表格的类名
      showTableControlPopup: false, // 新增属性，控制弹出层显示
    };
  },
  mounted() {
    this.quillEditor = new Quill(this.$refs.editor, {
      theme: 'bubble', // 或者你可以选择 'bubble' 主题来完全隐藏默认工具栏
      modules: {
        table: true // 启用表格模块
      }
    });
  },
  methods: {
    goBack() {
      this.$router.push('/');
    },
    finishNote() {
    },
    undo() {
      this.quillEditor.history.undo();
    },
    redo() {
      this.quillEditor.history.redo();
    },
    toggleAddMenu() {
      this.addMenuVisible = !this.addMenuVisible;
    },
    insertImage() {
      const range = this.quillEditor.getSelection();
      let index = range ? range.index : this.quillEditor.getLength();
      // 创建一个隐藏的文件选择对话框
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*'; // 只允许选择图片文件

      input.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const imageURL = e.target.result;
            this.quillEditor.insertEmbed(index, 'image', imageURL, Quill.sources.USER);
          };
          reader.readAsDataURL(file); // 读取文件内容作为 data URL
        }
      });

      input.click(); // 模拟点击文件选择对话框
      this.addMenuVisible = false;
    },
    insertAudio() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'audio/*'; // 只允许选择音频文件

      input.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
          // 在实际应用中，您应该上传文件到服务器并获取文件的URL
          // 这里我们仅使用文件的本地路径作为示例（这在实际应用中并不可用）
          const audioLink = URL.createObjectURL(file);
          const range = this.quillEditor.getSelection();
          let index = range ? range.index : this.quillEditor.getLength();
          this.quillEditor.insertText(index, audioLink, 'link', 'user');
        }
      });

      input.click();
      this.addMenuVisible = false;
    },
    insertTable() {
      const range = this.quillEditor.getSelection();
      let index = range ? range.index : this.quillEditor.getLength();

      const tableId = ++this.tableIdCounter;
      const tableClass = `custom-table-${tableId}`;
      this.selectedTableClass = tableClass;

      const tableHTML = `
        <table class="${tableClass}">
          <tr><td>Cell 1</td><td>Cell 2</td></tr>
          <tr><td>Cell 3</td><td>Cell 4</td></tr>
        </table>
        `;

      this.quillEditor.clipboard.dangerouslyPasteHTML(index, tableHTML);
      this.addMenuVisible = false;

      // 等待表格插入完成
      this.$nextTick(() => {
        const tables = this.quillEditor.root.querySelectorAll('table');
        const lastTable = tables[tables.length - 1];
        if (lastTable) {
          lastTable.classList.add(tableClass);
        }
      });
    },
    // 行
    addRow() {
      if (this.selectedTableClass) {
        const tableContainer = this.quillEditor.root.querySelector(`table.${this.selectedTableClass}`).parentNode;
        const table = tableContainer.querySelector(`table.${this.selectedTableClass}`);
        const rowCount = table.rows.length;

        if (rowCount < 50) {
          const row = table.insertRow();
          for (let i = 0; i < table.rows[0].cells.length; i++) {
            const cell = row.insertCell();
            cell.innerText = `New Cell ${i + 1}`;
          }
        } else {
          console.warn('Cannot add more rows. Maximum is 50.');
        }
      } else {
        console.warn('No table selected');
      }
    },
    //列
    addColumn() {
      if (this.selectedTableClass) {
        const tableContainer = this.quillEditor.root.querySelector(`table.${this.selectedTableClass}`).parentNode;
        console.log('tableContainer',tableContainer)
        const table = tableContainer.querySelector(`table.${this.selectedTableClass}`);
        console.log('table',table)
        const columnCount = table.rows[0].cells.length;

        if (columnCount < 7) {
          for (let row of table.rows) {
            console.log('row', row)
            row.insertCell();
            // cell.innerText = `New Cell ${row.cells.length}`;
          }
        } else {
          console.warn('Cannot add more columns. Maximum is 7.');
        }
      } else {
        console.warn('No table selected');
      }
    },

    deleteRow() {
      if (this.selectedTableClass) {
        const tableContainer = this.quillEditor.root.querySelector(`table.${this.selectedTableClass}`).parentNode;
        const table = tableContainer.querySelector(`table.${this.selectedTableClass}`);
        const rowCount = table.rows.length;

        if (rowCount > 1) {
          table.deleteRow(rowCount - 1);
        } else {
          console.warn('Cannot delete row. At least one row must remain.');
        }
      } else {
        console.warn('No table selected');
      }
    },

    deleteColumn() {
      if (this.selectedTableClass) {
        const tableContainer = this.quillEditor.root.querySelector(`table.${this.selectedTableClass}`).parentNode;
        const table = tableContainer.querySelector(`table.${this.selectedTableClass}`);
        const columnCount = table.rows[0].cells.length;

        if (columnCount > 1) {
          for (let row of table.rows) {
            row.deleteCell(row.cells.length - 1);
          }
        } else {
          console.warn('Cannot delete column. At least one column must remain.');
        }
      } else {
        console.warn('No table selected');
      }
    },

    checkTableSelection(event) {
      this.$nextTick(() => {
        const target = event.target;
        const table = target.closest('table');
        console.log('table', table)
        if (table) {
          const tableClass = table.className.split(' ').find(cls => cls.startsWith('custom-table-'));
          console.log('tableClass',tableClass)
          if (tableClass) {
            this.selectedTableClass = tableClass;
            this.showTableControls = true;
          } else {
            this.showTableControls = false;
            this.selectedTableClass = null;
          }
        } else {
          this.showTableControls = false;
          this.selectedTableClass = null;
        }
      });
    },
  },
};
</script>

<style scoped>
.note-add-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  height: 10%;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.finish-button {
  margin-left: 10px;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow-y: auto;
  height: 80%;
}

.title-input {
  margin-bottom: 10px;
}

.content-editor {
  flex: 1;
  border: 1px solid darkgrey;
}

.quill-editor {
  height: 100%;
}

.bottom-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f5f5;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  height: 10%;
}

.add-menu-scroll-container {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 10px;
}

.add-menu-content {
  display: flex;
  align-items: center;
}

.add-menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px; /* 水平间距 */
}

.icon-container {
  margin-bottom: 4px; /* 图标和文字之间的间距 */
}

.text-container {
  text-align: center;
}

/* 自定义弹出层样式 */
.custom-add-menu .el-dialog__header {
  display: none; /* 隐藏标题栏 */
}

.custom-add-menu .el-dialog__body {
  padding: 0; /* 去掉默认内边距 */
}

.custom-add-menu .el-dialog {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  margin-top: -10px; /* 根据需要调整与按钮的距离 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
.table-controls {
  position: absolute;
  z-index: 10;
  background: white;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 5px;
}
.table-control-button {
  margin: 5px;
}
</style>